package com.openspring.platform.controller;

import java.util.Map;
import javax.annotation.Resource;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import com.openspring.framework.common.Paging;
import com.openspring.framework.controller.GenericController;
import com.openspring.framework.tree.Node;
import com.openspring.framework.util.ResultUtils;
import com.openspring.platform.model.Role;
import com.openspring.platform.service.RoleService;

@Controller
@RequestMapping("role")
public class RoleController extends GenericController<Role, Long>{

	private RoleService roleService;

	@Resource(name="roleService")
	public void setRoleService(RoleService roleService) {
		super.setGenericService(roleService);
		this.roleService = roleService;
	}
	
	@RequestMapping(value="/create", method=RequestMethod.POST)
	@ResponseBody
	public Map<String, Object> create(@ModelAttribute Role entity) {
		roleService.create(entity);
		return ResultUtils.data(entity);
	}

	@RequestMapping(value="/modify", method=RequestMethod.POST)
	@ResponseBody
	public Map<String, Object> modify(@ModelAttribute Role entity) {
		roleService.modify(entity);
		return ResultUtils.data(entity);
	}
	
	@RequestMapping(value="/remove", method=RequestMethod.POST)
	@ResponseBody
	public Map<String, Object> remove(@RequestParam("id") Long[] id) {
		if(id.length == 1)
			roleService.remove(id[0]);
		else
			roleService.remove(id);
		return ResultUtils.success();
	}
	
	@RequestMapping(value="/load/{id}", method=RequestMethod.GET)
	@ResponseBody
	public Map<String, Object> load(@PathVariable("id") Long id) {
		return ResultUtils.data(roleService.load(id));
	}
	
	@RequestMapping(value="/list", method=RequestMethod.GET)
	@ResponseBody
	public Map<String, Object> list(
			@ModelAttribute Paging paging,
			@RequestParam(value="filter", required=false) String filter,
			@RequestParam(value="sort", required=false) String sort) {
		
		return this.doQuery(paging, filter, sort);
	}
	
	@RequestMapping(value="/queryuserroletree/{id}", method=RequestMethod.GET)
	@ResponseBody
	public Node queryUserRoleTree(@PathVariable("id") Long id) {
		return roleService.getUserRoleTree(id);
	}
	
	@RequestMapping(value="/saveuserrole", method=RequestMethod.POST)
	@ResponseBody
	public Map<String, Object> saveUserRole(@RequestParam("id") Long id, @RequestParam(value="ids", required=false) Long...ids) {
		roleService.saveUserRole(id, ids);
		return ResultUtils.success();
	}
}